<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>
    <el-form
      :model="form"
      ref="form"
      size="small"
      label-width="68px"
      label-position="left"
      :rules="rules"
      style="display: flex; flex-wrap: wrap; width: 80%; margin: 0 auto"
    >
      <el-form-item label="班组名称" prop="wgName">
        <el-input
          v-model="form.wgName"
          placeholder="请输入班组名称"
          clearable
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="班组类型" prop="wgGTypeCode">
        <el-select
          v-model="form.wgGTypeCode"
          placeholder="请选择班组类型"
          clearable
        >
          <el-option
            v-for="t in allGroupTypes"
            :key="t.groupCode"
            :label="t.groupTypeName"
            :value="t.groupCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="wgManager">
        <MyPopoverBtn placeholder="请选择负责人"
                      :content="form.selectedManager && form.selectedManager.userName ? form.selectedManager.userName : ''"
                      @click="openManagerDialog"
        />
      </el-form-item>
      <el-form-item label="状态" prop="wgStatus">
        <el-radio-group v-model="form.wgStatus">
          <el-radio v-for="s in getStatus" :key="s.value" :label="s.value">
            {{ s.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="wgDesc" class="my-desc">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          placeholder="请输入备注"
          v-model="form.wgDesc"
        />
      </el-form-item>
    </el-form>


    <el-divider>
      <div class="my-divider">班组成员</div>
    </el-divider>
    <el-button type="primary" @click="handleGroupPeo">添加</el-button>
    <el-button type="primary" plain
               @click="handleRemoveGroupPeo"
    >移除
    </el-button>
    <el-table
      :data="groupPeo"
      @selection-change="selectChangeGroupPeo"
      row-key="userId"
    >
      <el-table-column
        type="selection"
        align="center"
      />
      <el-table-column
        type="index"
        align="center"
        label="序号"
      />
      <el-table-column label="成员姓名" align="center" prop="userId" />
      <el-table-column label="所在部门" align="center" prop="dept.deptName" />
      <el-table-column label="岗位" align="center" prop="postId">
        <template slot-scope="scope">
          <el-tag
            style="margin: 10px 5px"
            v-for="tag in scope.row.userPosts"
            :key="tag.postId"
          >{{ tag.postName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phonenumber" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="deleteRowGroupPeo(scope.$index)"
            type="text"
            size="small"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    选择负责人-->
    <el-dialog title="选择负责人" :visible.sync="dialogVisible1" width="50%" append-to-body>
      <div class="tag-box">
        <el-tag
          style="margin: 10px 5px"
          closable
          @close="handleCloseManager"
          v-if="preSelectedManager && preSelectedManager.userName"
        >
          {{ preSelectedManager.userName }}
        </el-tag>
      </div>

      <div class="check-box">
        <el-input
          v-model="deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
        <el-row style="max-height: 360px; overflow-y: scroll">
          <el-col :span="12">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </el-col>
          <el-col :span="12">
            <el-table ref="managerTable" :data="managerList"
                      @selection-change="selectChangeToPrePeo"
                      highlight-current-row
                      @current-change="handleManagerChange"
            >
              <el-table-column prop="userName" align="left" label="负责人" />
            </el-table>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okManager">确 定</el-button>
        <el-button @click="cancelManager">取 消</el-button>
      </div>
    </el-dialog>

    <!--    选择人员-->
    <el-dialog title="选择人员" :visible.sync="dialogVisible2" width="50%" append-to-body @open="openUserDialog">
      <div class="tag-box">
        <el-tag
          style="margin: 10px 5px"
          v-for="tag in preSelectedGroupPeo"
          :key="tag.userId"
          closable
          @close="handleCloseGroupPeo(tag)"
        >
          {{ tag.userName }}
        </el-tag>
      </div>

      <div class="check-box">
        <el-input
          v-model="deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
        <el-row style="max-height: 360px; overflow-y: scroll">
          <el-col :span="12">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            />
          </el-col>
          <el-col :span="12">
            <el-table ref="userTable" :data="groupPeoList" @selection-change="selectChangeToPrePeo" row-key="userId">
              <el-table-column prop="userName" align="left">
                <template slot="header" slot-scope="scope">
                  已选({{ preSelectedGroupPeo ? preSelectedGroupPeo.length : 0
                  }}/{{ groupPeoList ? groupPeoList.length : 0 }})
                </template>
              </el-table-column>
              <el-table-column type="selection" align="right" />
            </el-table>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okGroupPeo">确 定</el-button>
        <el-button @click="cancelGroupPeo">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />
  </div>
</template>
<script>
import { allGroupType } from '@/api/yyj/pbs/groupType'
import { allUser, deptTreeSelect } from '@/api/system/user'
import MyPopoverBtn from '@/components/MyPopoverBtn/index.vue'
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'
import { addWorkGroup, getWorkGroup, updateWorkGroup } from '@/api/yyj/pbs/workGroup'
import MyPostTag from '@/components/MyPostTag/index.vue'

export default {
  name: 'GroupTypeChange',
  components: { MyPostTag, MyConfirmBtnGroup, MyPopoverBtn },
  dicts: ['yyj_common_status'],
  data() {
    return {
      backPage: '/pbs/workGroup',
      innerVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      // 表单参数
      form: {
        wgStatus: '1'
      },
      // 表单校验
      rules: {
        wgName: [
          { required: true, message: '班组名称不能为空', trigger: 'blur' }
        ],
        wgGTypeCode: [
          { required: true, message: '生产班组类型不为空', trigger: 'change' }
        ],
        wgManager: [
          { required: true, message: '负责人不能为空', trigger: 'blur' }
        ]
      },
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      deptName: undefined,
      allGroupTypes: [],
      // 选择的班组成员
      selectedGroupPeo: [],
      preSelectedManager: {},
      // 将删除的班组成员
      preRemovedGroupPeo: [],
      // 预选班组成员
      preSelectedGroupPeo: [],
      // 用户表格数据
      managerList: [],
      groupPeoList: [],
      postOptions: [],
      // 查询参数
      userQueryParams: {
        userName: undefined,
        phonenumber: undefined,
        status: '0',
        deptId: undefined
      },
      // 生产单元
      preSelectedWorkCell: {}
    }
  },
  created() {
    const wgCode = this.$route.params.wgCode
    if (wgCode) {
      this.form.wgCode = wgCode
      Promise.all([this.getWorkGroupByCode(wgCode), this.getAllType(), this.getDeptTree(), this.getUserList()])
    } else {
      Promise.all([this.getAllType(), this.getDeptTree(), this.getUserList()])
    }
  },
  computed: {
    getStatus() {
      return this.dict.type.yyj_common_status
    },
    groupPeo() {
      return this.selectedGroupPeo
    }
  },
  methods: {
    // 获取当前的详细信息
    async getWorkGroupByCode(wgCode) {
      const res = await getWorkGroup(wgCode)
      this.form = res.data
      this.selectedGroupPeo = res.groupPeos
      this.form.selectedManager = res.manager
    },
    okManager() {
      this.form.selectedManager = { ...this.preSelectedManager }
      this.form.wgManager = this.form.selectedManager.userId
      this.cancelManager()
    },
    cancelManager() {
      this.deptName = ''
      this.preSelectedManager = {}
      this.dialogVisible1 = false
    },
    // 删除预选负责人
    handleCloseManager() {
      this.preSelectedManager = {}
      this.$refs.managerTable.setCurrentRow()
    },
    // 确认负责人
    handleManagerChange(val) {
      this.preSelectedManager = val
    },
    // 打开负责人
    openManagerDialog() {
      this.preSelectedManager = this.form.selectedManager
      this.dialogVisible1 = true
    },
    // 打开班组人员
    openUserDialog() {
      this.preSelectedGroupPeo = this.selectedGroupPeo
      this.$nextTick(() => {
        if (this.preSelectedGroupPeo && this.preRemovedGroupPeo.length > 0) {
          // this.preSelectedGroupPeo.forEach((e, i) => {
          this.$refs.userTable.selection = this.preSelectedGroupPeo
          // })
        }
      })
    },
    /** 查询用户列表 */
    async getUserList() {
      const res = await allUser(this.userQueryParams)
      this.groupPeoList = res.data
      this.managerList = res.data
    },
    /** 查询部门下拉树结构 */
    async getDeptTree() {
      const res = await deptTreeSelect()
      this.deptOptions = res.data
    },
    // 删除节点
    handleCloseGroupPeo(tag) {
      this.preSelectedGroupPeo = this.preSelectedGroupPeo.filter(e => {
        if (e.userId !== tag.userId) {
          return true
        }
        this.$refs.userTable.toggleRowSelection(e, false)
        return false
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.userQueryParams.deptId = data.id
      this.userQueryParams.pageNum = 1
      this.getUserList()
    },
    // 确认弹出框
    okGroupPeo() {
      this.selectedGroupPeo = [...this.preSelectedGroupPeo]
      this.cancelGroupPeo()
    },
    // 取消弹出框
    cancelGroupPeo() {
      this.deptName = ''
      this.preSelectedGroupPeo = []
      this.$refs.userTable.clearSelection()
      this.dialogVisible2 = false
    },
    // 去添加班组成员
    handleGroupPeo() {
      this.dialogVisible2 = true
    },
    // 移除班组成员
    handleRemoveGroupPeo() {
      this.preRemovedGroupPeo.forEach(e1 => {
          this.selectedGroupPeo =
            this.selectedGroupPeo.filter(e2 => e2.userId !== e1.userId)
        }
      )
    },
    // 班组成员改变多选框改变事件
    selectChangeGroupPeo(selection) {
      this.preRemovedGroupPeo = selection
    },
    selectChangeToPrePeo(selection) {
      this.preSelectedGroupPeo = selection
    },
    // 删除班组成员表格行数据
    deleteRowGroupPeo(index) {
      this.selectedGroupPeo.splice(index, 1)
    },
    /**
     * 获取所有班组类型
     */
    async getAllType() {
      const res = await allGroupType()
      this.allGroupTypes = res.data
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.selectedGroupPeo = this.selectedGroupPeo.map(e => {
            return {
              wgroupPeo: e.userId
            }
          })
          this.form.pbsWorkGroupPeos = this.selectedGroupPeo
          console.log(this.form)
          this.$modal.loading('正在提交...')
          if (this.form.wgCode != null) {
            // 两个东西
            await updateWorkGroup(this.form)
            this.$modal.msgSuccess('修改成功')
          } else {
            await addWorkGroup(this.form)
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    }
  }
}
</script>
<style scoped lang="scss">
.my-divider {
  border: 1px solid rgb(220, 223, 230);
  padding: 5px;
  border-radius: 5px;
  color: #409eff;
}

.el-form-item {
  width: 50%;
  margin-right: 0px !important;
  padding-left: 15%;
  white-space: nowrap;
}

.my-input {
  width: 205px;
}

.my-desc {
  width: 90%;
}

.my-img-box {
  height: 50%;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

.upload-demo .el-upload {
  width: 100%;
}

.tag-box {
  min-height: 72px;
  margin-bottom: 20px;
  border: 1px dashed rgb(220, 223, 230);
}

</style>
